<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <el-form :inline="true" size="medium">
            <template v-if="inout != 0">
              <el-form-item>
                <el-button type="primary" @click="showGarageForm">
                  <span v-if="inout == 1">入库</span>
                  <span v-if="inout == 2">出库</span>
                </el-button>
              </el-form-item>
            </template>
          </el-form>

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>
      <el-table-column
        prop="siteName"
        label="场地"
        min-width="120">
      </el-table-column>

      <el-table-column
        prop="currentStatus"
        label="状态"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.currentStatus==1">未入库</span>
          <span v-else-if="scope.row.currentStatus==2">已入库</span>
          <span v-else-if="scope.row.currentStatus==3">已出库</span>
          <span v-else-if="scope.row.currentStatus==4">已提车</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="garageType"
        label="库类型"
        min-width="120">
        <template scope="scope">
          <span v-if="scope.row.garageType==1">待检库</span>
          <span v-else-if="scope.row.garageType==2">完成库</span>
          <span v-else-if="scope.row.garageType==3">问题车型库</span>
          <span v-else-if="scope.row.garageType==4">待检无任务库</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="carStatus"
        label="车辆状态"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="carLocation"
        label="车辆位置"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="name"
        label="产品名称"
        min-width="120">
      </el-table-column>
      
      <el-table-column
        prop="model"
        label="产品型号"
        min-width="120">
      </el-table-column>
      <!-- <el-table-column
        prop="carImg1"
        label="图片1"
        min-width="120">
        <template scope="scope">
          <el-image v-if="scope.row.carImg1" :src="fileBaseUrl+scope.row.carImg1" :preview-src-list="[fileBaseUrl+scope.row.carImg1]" fit="contain" style="width: 120px;height: 120px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="carImg2"
        label="图片2"
        min-width="120">
        <template scope="scope">
          <el-image v-if="scope.row.carImg2" :src="fileBaseUrl+scope.row.carImg2" :preview-src-list="[fileBaseUrl+scope.row.carImg2]" fit="contain" style="width: 120px;height: 120px;"></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="carImg3"
        label="图片3"
        min-width="120">
        <template scope="scope">
          <el-image v-if="scope.row.carImg3" :src="fileBaseUrl+scope.row.carImg3" :preview-src-list="[fileBaseUrl+scope.row.carImg3]" fit="contain" style="width: 120px;height: 120px;"></el-image>
        </template>
      </el-table-column> -->


      <el-table-column
        prop="note"
        label="备注"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="createUserName"
        label="操作人"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="操作时间"
        min-width="160">
        <template scope="scope">
          {{fmtDate(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="操作"
        min-width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showFile(scope.$index, scope.row)">显示内容</el-button>
          <!-- <el-button size="mini" type="primary" v-if="scope.row.status==3||scope.row.status==4?true:false"  @click="handleEdit(scope.$index, scope.row)">重新上传</el-button>
          <el-button size="mini" type="danger"   @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">
        <el-form-item label="检测场地" label-width="100px" prop="siteId">
          <el-select v-model="editForm.siteId" placeholder="请选择">
            <el-option
              v-for="item in testSiteList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库类型" label-width="100px" prop="garageType">
          <el-select v-model="editForm.garageType" placeholder="请选择">
            <el-option :key="1" label="待检库" :value="1"></el-option>
            <el-option :key="2" label="完成库" :value="2"></el-option>
            <el-option :key="3" label="问题车型库" :value="3"></el-option>
            <el-option :key="4" label="待检无任务库" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆位置" label-width="100px" prop="carLocation">
          <el-input v-model="editForm.carLocation" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="车辆状态" label-width="100px" >
          <el-input v-model="editForm.carStatus" autocomplete="off"></el-input>
        </el-form-item>

        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-success="handleAvatarSuccess"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          multiple
          :file-list="fileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
        </el-upload>

        <el-upload
          class="avatar-uploader"
          :action="uploadActionUrl"
          :on-success="handleAvatarSuccessVideo"
          :on-preview="handlePreview"
          :on-remove="handleRemoveVideo"
          multiple
          :file-list="fileVideoList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4/avi文件</div>
        </el-upload>

        <!-- 照片上传 -->
        <!-- <el-form-item label="照片1" label-width="100px" prop="carImg1">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadActionUrl"
            accept=".png,.jpeg,.jpg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload1"
            :on-error="handleAvatarError">
            <img v-if="editForm.carImg1" :src="fileBaseUrl+editForm.carImg1" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="照片2" label-width="100px" prop="carImg2">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadActionUrl"
            accept=".png,.jpeg,.jpg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload2"
            :on-error="handleAvatarError">
            <img v-if="editForm.carImg2" :src="fileBaseUrl+editForm.carImg2" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="照片3" label-width="100px" prop="carImg3">
          <el-upload
            class="avatar-uploader"
            name="file"
            :action="uploadActionUrl"
            accept=".png,.jpeg,.jpg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload3"
            :on-error="handleAvatarError">
            <img v-if="editForm.carImg3" :src="fileBaseUrl+editForm.carImg3" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->

        <el-form-item label="备注" label-width="100px">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">
          <span v-if="inout == 1">入库</span>
          <span v-if="inout == 2">出库</span>
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imgDialogVisible" width="650px">
      <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">

      <template v-for="(item,index) in picFiles">
        <el-image
            style="width: 500px;margin-top: 8px;"
            :src="fileBaseUrl + item"
            :preview-src-list="[fileBaseUrl + item]"
            v-if="!isVideo(item)">
          </el-image>
      </template>
      <template v-for="(item,index) in videoFiles">
        <div style="margin-top: 8px;">
        <video width="500px" :src="fileBaseUrl + item" alt="" controls="controls" v-if="isVideo(item)">
          您的浏览器无法播放视频
        </video>
        </div>
      </template>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getTestGarageList, addTestGarage, updateTestGarage, deleteTestGarage} from "../../../api/test_garage.js";
import {getAllTestSiteList} from '../../../api/test_site.js'
import {getToken} from '../../../common/utils/auth.js'
import {getFileUrl} from '../../../api/file.js'

export default {
  name: "testGarageManage",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      fileList:[],
      fileVideoList:[],
      editForm: {
        id: 0,
        siteId: '', // 检测场地id
        currentStatus: '', // 当前状态 1 未入库 2 已入库 3 已出库 4 已提车
        carId: '', // 车辆id
        // dataStatus: '', // 数据状态 0 过去 1 当前
        garageType: '', // 库类型: 1 待检库 2 完成库
        carStatus: '', // 车辆状态
        carLocation:'',//车辆位置

        fileList:[],
        fileVideoList:[],
        note: '',
      },
      editRules: {
        siteId: [{ required: true, message:"请选择检测场地", trigger: 'blur'}],
        garageType: [{ required: true, message:"请选择库类型", trigger: 'blur'}],
        carLocation: [{ required: true, message:"请输入车辆位置", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {

      },
      testSiteList:[],
      carId:'',
      last:'',
      uploadActionUrl:'',
      uploadKey:'',
      fileBaseUrl:'',
      picFiles:[],
      videoFiles:[],
      imgDialogVisible:false,
    }
  },
  computed:{
    inout(){
      if(util.isEmpty(this.last)){
        return 0;
      }
      if(this.last.currentStatus == 1){ // 未入库
        return 1;
      }else if(this.last.currentStatus == 2){ // 已入库
        return 2;
      }else if(this.last.currentStatus == 3){ // 已出库
        return 1;
      }else if(this.last.currentStatus == 4){ // 已提车
        return 0;
      }else{
        return 0;
      }
    }
  },
  mounted() {
    let carId=this.$route.params.carId;
    this.carId = carId;

    this.init();

    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }

    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/get?_t="+t+"&f=";
  },
  methods: {
    isVideo(val){
      if(util.isEmpty(val)){
        return false;
      }
      if(val.toLowerCase().indexOf(".avi") != -1 || val.toLowerCase().indexOf(".mp4") != -1){
        return true;
      }
      return false;
    },

    handleRemove(file, fileList) {

      this.fileList = fileList;
      let data = [];
      // console.log(this.fileList.length)
      for(var i=0;i<this.fileList.length;i++){

        // console.log(fileList[i].response.data)
        data.push(fileList[i].response.data)
      }
      this.editForm.fileList = data;
      // this.editForm.fileList = fileList;

            // console.log(file, fileList);
      },
      handleRemoveVideo(file, fileVideoList){
        this.fileVideoList = fileVideoList;
        let data = [];
        // console.log(this.fileList)
        for(var i=0;i<this.fileVideoList.length;i++){
          // console.log(fileList[i].response.data)
          data.push(fileVideoList[i].response.data)
        }
        this.editForm.fileVideoList = data;
      },

    showFile(index,row){
      // console.log(row)
      if(util.isEmpty(row.url)){
        this.$message.error("未发现文件");
        return;
      }
      let fileTypeArr = row.fileType.split(",");
      let urlArr = row.url.split(",");
      let picFiles = [];
      let videoFiles = [];

      for(let i in fileTypeArr){
        if(fileTypeArr[i] == "1"){
          picFiles.push(urlArr[i]);
        }else if(fileTypeArr[i] == "2"){
          videoFiles.push(urlArr[i]);
        }
      }

      this.picFiles = picFiles;
      this.videoFiles = videoFiles;

      this.imgDialogVisible = true;
    },
    getFileUrl(){

    },
    handlePreview(file) {
            // console.log(file);
          },
    // beforeRemove(file, fileList) {
    //     return this.$confirm(`确定移除 ${ file.name }？`);
    //   },



    handleAvatarSuccess(res, file, fileList){
      // this.avatarUploadLoadingDiv.close();
      if (res.code == 1){
        this.fileList = fileList;
        let data = [];
        // console.log(this.fileList)
        for(var i=0;i<this.fileList.length;i++){
          // console.log(fileList[i].response.data)
          if(fileList[i].response!=null&&fileList[i].response!=''){
            data.push(fileList[i].response.data)
          }

        }
        this.editForm.fileList = data;
        // console.log(this.editForm.fileList)
        // this.fileList = fileList;
        // console.log("++++++++++++++++++");
        // console.log(this.editForm.fileList);
        // console.log(this.res.data);
        // console.log("++++++++++++++++++");
        return;
      }else{
        this.$message({
          message: res.msg,
          type: 'warning'
        });
      }
    },
    handleAvatarSuccessVideo(res, file, fileVideoList){
      // this.avatarUploadLoadingDiv.close();
      if (res.code == 1){
        this.fileVideoList = fileVideoList;
        let data = [];
        // console.log(this.fileList)
        for(var i=0;i<this.fileVideoList.length;i++){
          // console.log(fileList[i].response.data)
          if(fileVideoList[i].response!=null&&fileVideoList[i].response!=''){
            data.push(fileVideoList[i].response.data)
          }
        }
        this.editForm.fileVideoList = data;
        // console.log(this.editForm.fileVideoList)
        // this.fileList = fileList;
        // console.log("++++++++++++++++++");
        // console.log(this.editForm.fileList);
        // console.log(this.res.data);
        // console.log("++++++++++++++++++");
        return;
      }else{
        this.$message({
          message: res.msg,
          type: 'warning'
        });
      }
    },
    beforeAvatarUpload1(){
      this.uploadKey='carImg1';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },
    beforeAvatarUpload2(){
      this.uploadKey='carImg2';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },
    beforeAvatarUpload3(){
      this.uploadKey='carImg3';
      this.avatarUploadLoadingDiv = util.showLoading("照片上传中");
    },
    handleAvatarError(){
      this.avatarUploadLoadingDiv.close();
      this.$message({
        message: "照片上传失败,请检查网络",
        type: 'warning'
      });
    },
    init(){
      getAllTestSiteList().then(res => {
        if(res.code == 1) {
          this.testSiteList = res.data;
        }
      }).catch(res => {

      })
    },

    isEmpty(val){
      return util.isEmpty(val);
    },

    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },

    showGarageForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

      for(let key in this.last){
        this.editForm[key] = '';
      }


      this.editForm.siteId = this.last.siteId;
      this.editForm.garageType = this.last.garageType;
      if(this.inout == 1){
        this.editForm.currentStatus = 2;
      }else if(this.inout == 2){
        this.editForm.currentStatus = 3;
      }
      this.editForm.fileVideoList = [];
      this.editForm.fileList = [];
      this.fileList = [];
      this.fileVideoList = [];
      this.editForm.carId = this.carId;
      this.editForm.id = 0;
      this.editFormVisible = true;
    },
    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }

    },
    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {

          // 如果是入库 场地id 库类型必选
          if(this.inout == 1){
            if(util.isEmpty(this.editForm.siteId)){
              this.$message({
                showClose: true,
                message: "请选择场地",
                type: 'error'
              });
              return;
            }

            if(util.isEmpty(this.editForm.garageType)){
              this.$message({
                showClose: true,
                message: "请选择库类型",
                type: 'error'
              });
              return;
            }

          }


          this.loading = true;
          let loadingText = "";
          if(this.inout == 1){
            loadingText = "入库中...";
          }else if(this.inout == 2){
            loadingText = "出库中...";
          }
          const loadingDiv = util.showLoading(loadingText)

          addTestGarage(this.editForm).then(res => {
            let title = ""
            if(this.inout == 1){
              title = "入库";
            }else if(this.inout == 2){
              title = "出库";
            }

            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteTestGarage({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getTestGarageList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        carId: this.carId,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
          this.last = data.last;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(1)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
